<?php

require_once 'Framework/Controller/Action.php';

/**
 * Профиль
 *
 */
class ProfileController extends Framework_Controller_Action
{
    /**
     * Я
     *
     * @var obj User_Self
     */
    private $_user;
    
    private $_data;
	
	private $_ua;
	private $_ip;
    
    const MESSAGES = 5;
    const FRIEND  = 10;
    const BLACK   = 10;
    const VISITOR = 10;
    
    /**
     * Тексты сообщений об ошибках
     *
     */
    private $_messages;
    
    public function init()
    {
        // Если не авторизирован то пшел вон
        if (!$this->session->get('logged_in')) {
            $this->session->set('http_referer', $this->getRequest()->getServer('REDIRECT_URL'));
            $this->_redirect('/user/login/');
        }
		
		$this->_ua = $this->getRequest()->getServer('HTTP_USER_AGENT');
		$this->_ip = $this->getRequest()->getServer('REMOTE_ADDR');
		Stat_Access::setAccess(100,$this->_ua,$this->_ip); // 100 - any other page besides main
		
        $this->_user = new User_Self($this->session->get('user_id'));
        $this->view->messages_count = $this->_user->getNewMessagesCount();
        $this->_messages = Framework_Registry::get('messages');
        
        $this->_data = $this->_user->getAllData();
        $this->view->data = $this->_data;
    }
    
    /**
     * Профайл
     *
     */
    public function indexAction()
    {
        // Отключаем кеширование
        $this->getResponse()->noCache();
        //Зачищаем юзера в комнатах
        Room::clean($this->session->get('user_login'));
        $total_visitors = $this->_user->getTotalVisitors();
        $this->view->total_visitors = $total_visitors;
        
        $this->view->messages_count = $this->_user->getNewMessagesCount();

        $this->render();
    }
    
    /**
     * Список друзей
     *
     */
    public function friendAction()
    {
        $page = $this->_getParam(0,0);
        $friends = $this->_user->getFriends(self::FRIEND, $page, $paging);
        $this->view->friends = $friends;
        $this->view->paging  = $paging;
        $this->view->page    = $page;
        
        $this->render();
    }
    
    /**
     * Black list
     *
     */
    public function blackAction()
    {
        $page = $this->_getParam(0,0);
        $block_users = $this->_user->getBlockUsers(self::BLACK, $page, $paging);
        $this->view->block_users = $block_users;
        $this->view->paging   = $paging;
        $this->view->page     = $page;
        
        $this->render();
    }
    
    /**
     * Кто посещал мою анкету
     *
     */
    public function visitorAction()
    {
        $page = $this->_getParam(0,0);
        $visitors = $this->_user->getVisitors(self::VISITOR, $page, $paging);
        $this->view->visitors = $visitors;
        $this->view->paging   = $paging;
        $this->view->page     = $page;
        
        $this->render();
    }
    
    /**
     * Редактирование профиля
     *
     */
    public function editAction()
    {
        if ($this->getRequest()->getMethod() != 'POST') { // Показать форму с данными для изменения
            $this->view->month = substr($this->_data['user_born'], 5, 2);
            $this->view->year  = substr($this->_data['user_born'], 0, 4);
            $this->view->day   = substr($this->_data['user_born'], 8, 2);
            $this->session->set('user_mail', $this->_data['user_mail']);
            
            if ($this->session->get('password_change')) {
                $this->view->result = $this->_messages->user->changePassword;
            }
        } else if ($this->getRequest()->getPost('password')) { // Смена пароля
            $this->view->month = substr($this->_data['user_born'], 5, 2);
            $this->view->year  = substr($this->_data['user_born'], 0, 4);
            $this->view->day   = substr($this->_data['user_born'], 8, 2);
            
            $data = get_value($this->getRequest()->getPost('data'));
            if ($error = $this->_passwordValidate($data)) {
                $this->view->error = $error;
            } else {
                // Пытаемся установить новый пароль
                if ($this->_user->setNewPassword($data['password'], $data['old_password'])) {
                	$this->session->set('password_change', true);
                	$this->_redirect('/profile/edit/');
                } else {
                    $this->view->error = array('old_password' => $this->_messages->user->old_password);
                }
            }
        } else { // Изменение личных данных
            $data = get_value($this->getRequest()->getPost('data'));
            $data['month'] = $this->getRequest()->getPost('Date_Month');
            $data['day']   = $this->getRequest()->getPost('Date_Day');
            $data['year']  = $this->getRequest()->getPost('Date_Year');
            $data['user_born'] = $data['year']  . '-'
                               . $data['month'] . '-'
                               . $data['day'];
            // Ошибки при измененни данных
            if ($error = $this->_formValidate($data)) {
                $this->view->error = $error;
                $this->view->data  = $data;
                $this->view->month = $this->getRequest()->getPost('Date_Month');
                $this->view->year  = $this->getRequest()->getPost('Date_Year');
                $this->view->day   = $this->getRequest()->getPost('Date_Day');
            } else {
                // Меняем данные
                $this->_user->setData($data);
                $this->_redirect();
            }
        }
        
        $this->render();
    }

    /**
     * Список сообщений
     *
     */
    public function messagesAction()
    {
    	$a = $this->_getParam(0);
        if (isset($a)) {
            switch ($a) {
                case 'output':
                    $course = 'from';
                    break;
                default:
                    $course = 'to';
                    break;
            }
        } else {
            $course = 'to';
        }

        $page = $this->_getParam(1,0);
        $this->view->messages_list = $this->_user->getMessages($course, self::MESSAGES, $page, $paging);
        $this->view->paging = $paging;
        $this->view->page   = $page;
        $this->view->course = $course;
        
        $this->render(); 
    }
    
    /**
     * Удаление сообщение
     *
     */
    public function delmessageAction()
    {
        //TODO Вообще неверный подход. Изменять надо постом а не гетом. не знаю что на меня нашло ))
        if (!$this->_getParam(0)) {
            $this->_redirect('/index/error/');
        }
        $this->_user->delMessage($this->_getParam(0));
        $this->_redirect('/profile/messages/');
    }
    
    /**
     * Выбранное сообщение
     *
     */
    public function messageAction()
    {
        $this->_user->readMessage($this->_getParam(0));
        $this->view->message = $this->_user->getMessage($this->_getParam(0));
        //$this->view->history = $this->_user->getHistoryTalk($this->_getParam(0), $this->_getParam(1));

        $this->render(); 
    }
    
    // Настройки
    public function preferencesAction()
    {
        if ($this->getRequest()->getMethod() != 'POST') { // Показать форму с данными для изменения
            // Берем из базы текущие значения
            $this->view->form = $this->_user->getSettings();
        } else {
            $form = get_value($this->getRequest()->getPost('form'));
            // Валидируем
            $form['invite']  = !isset($form['invite']) ? 0 : 1;
            $form['private'] = !isset($form['private']) ? 0 : 1;
            $form['notific'] = !isset($form['notific']) ? 0 : 1;
            
            $this->_user->setSettings($form);
            
            $this->_redirect();
        }
        $this->render();
    }
    
    /**
     * Валидация формы
     *
     * @param array $form
     * @return array || false
     */
    private function _formValidate($form)
    {
        $errors = array();
        if (empty($form['user_mail']) ||
            empty($form['user_sex']) ||
            empty($form['user_born']) ||
            empty($form['user_country']) ||
            empty($form['user_city'])) {
                $errors['empty'] = $this->_messages->user->empty;
        }
        if (!@checkdate($form['month'], $form['day'], $form['year'])) {
            $errors['born'] = $this->_messages->user->wrongBorn;
        }
        if (!preg_match('[\w+@\w+.\w{2,4}]si', $form['user_mail'])) {
            $errors['mail'] = $this->_messages->user->wrongMail;
        } else if ($form['user_mail'] != $this->session->get('user_mail')
                && User_Self::findUserIdByMail($form['user_mail'])) {
            $errors['mail'] = $this->_messages->user->usedMail;
        }
        
        return sizeof($errors) ? $errors : false;
    }
    
    /**
     * Валидация пароля
     *
     * @param array $form
     * @return array || false
     */
    private function _passwordValidate($form)
    {
        $errors = array();
        if (empty($form['password'])
         || empty($form['password_again'])
         || empty($form['old_password'])) {
            $errors['password_empty'] = $this->_messages->user->empty; 	
        }
    	if ($form['password'] != $form['password_again']) {
    		$errors['password'] = $this->_messages->user->wrongPassword;
    	}
        if (strlen($form['password']) < 6) {
            $errors['password'] = $this->_messages->user->shortPassword;
        }
    	return sizeof($errors) ? $errors : false;
    }
}